package com.qbw.app.module.main.activity;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ToastUtil;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.MainActivityBinding;
import com.qbw.app.manager.LocationManager;
import com.qbw.app.model.Upload;
import com.qbw.app.model.Version;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.fragment.PhotoChooseDialogFragment;
import com.qbw.app.module.common.fragment.UpdateDialogFragment;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.home.fragment.HomeFragment;
import com.qbw.app.module.home.fragment.NewHomeFragment;
import com.qbw.app.module.mine.fragment.MineFragment;
import com.qbw.app.module.vehicle.fragment.VehicleTravelListFragment;
import com.qbw.app.module.warning.fragment.WarningFragment;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.app.request.impl.UserRequest;
import com.qbw.pu.PhotoUtil;
import com.tbox.tbsdk.HexUtil;
import com.tbox.tbsdk.TBoxSDK;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends CommonActivity<MainActivityBinding> implements PhotoChooseDialogFragment.Listener, PhotoUtil.CallBack {

    private final int AVATAR_SIZE = 140;
    private PhotoUtil mPhotoUtil;
    private final int REQ_CAMERA = 1;
    private final int REQ_GALLERY = 2;
    private final int REQ_CROP = 3;
    private TBoxSDK tBoxSDK;

    /**
     * 需要获取的权限
     */
    private final String[] mPermissions = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA
    };
    private final int RC_PERMISSION = 1;

    private MineFragment mMineFragment;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.main_activity;
    }

    @Override
    protected int getContainerViewId() {
        return R.id.container;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tBoxSDK = TBoxSDK.getInstance(this);
        addFragment(R.id.rb_home, HomeFragment.createInstance());
        addFragment(R.id.rb_travel, VehicleTravelListFragment.createInstance());
        addFragment(R.id.rb_mine, mMineFragment = MineFragment.createInstance());
        switchFragment(R.id.rb_home);
        mBinding.rbHome.setOnCheckedChangeListener((v, b) -> {
            if (b) {
                switchFragment(R.id.rb_home);
            }
        });
        mBinding.rbTravel.setOnCheckedChangeListener((v, b) -> {
            if (b) {
                switchFragment(R.id.rb_travel);
            }
        });
        mBinding.rbMine.setOnCheckedChangeListener((v, b) -> {
            if (b) {
                switchFragment(R.id.rb_mine);
            }
        });
        mPhotoUtil = new PhotoUtil(this, this, REQ_CAMERA, REQ_GALLERY, REQ_CROP);
        mPhotoUtil.setProviderNameAppend("fileprovider");
        if (!EasyPermissions.hasPermissions(this, mPermissions)) {
            EasyPermissions.requestPermissions(this,
                                               ResUtil.getString(R.string.app_need_permission),
                                               RC_PERMISSION,
                                               mPermissions);
        }
        mGeneralManager.getRequestManager()
                       .getUserRequest()
                       .updateInfo(JPushInterface.getRegistrationID(this), null, null, null, null)
                       .execute();
//        if(!XApplication.getInstance().isCheckUpdate()) {
//            mGeneralManager.getRequestManager().getCommonRequest().checkUpdate(this).execute();
//        }

    }



    private void connectDevice(BluetoothDevice bluetoothDevice) {
        TBoxSDK.getInstance(this).connectDevice(bluetoothDevice, new TBoxSDK.DeviceConnectingListener() {
            @Override
            public void onDeviceConnected() {
                ToastUtil.showToast(MainActivity.this,bluetoothDevice.getName() + " 连接成功");
            }

            @Override
            public void onDeviceConnectFailed(int errorCode) {
                ToastUtil.showToast(MainActivity.this,bluetoothDevice.getName() + " 连接失败");
            }

            @Override
            public void onDeviceDisconnected(int errorCode) {
                ToastUtil.showToast(MainActivity.this,bluetoothDevice.getName() + " 断开连接");

            }

            @Override
            public void onRssiUpdated(int rssi) {
            }

            @Override
            public void onDeviceStatusSync(TBoxSDK.LockStatus lockStatus, TBoxSDK.DefendStatus defendStatus, TBoxSDK.ACCStatus accStatus) {
//                showMessage("BLE 同步数据：" +
//                        "lockStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)lockStatus.getStatus()}) + "], " +
//                        "defendStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)defendStatus.getStatus()}) + "], " +
//                        "accStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)accStatus.getStatus()}) + "]");
            }
        });
    }


    @Override
    public void onClickPhotoChooseCancel() {

    }

    @Override
    public void onClickPhotoChooseCamera() {
        mPhotoUtil.getPhotoFromCamera(AVATAR_SIZE, AVATAR_SIZE);
    }

    @Override
    public void onClickPhotoChooseGallery() {
        mPhotoUtil.getPhotoFromGallery(AVATAR_SIZE, AVATAR_SIZE);
    }

    @Override
    public void onPhotoCamera(String s) {

    }

    @Override
    public void onPhotoGallery(String s) {

    }

    @Override
    public void onPhotoCrop(String s) {
        showLoadingDialog(R.string.uploading);
        mGeneralManager.getRequestManager().getCommonRequest().uploadFile(s, this).execute();
    }

    @Override
    public void onPhotoCancel() {

    }

    @Override
    public void onPhotoFailed() {

    }

    public boolean isHavePhotoChoosePermission() {
        String[] perms = new String[]{
                Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        if (EasyPermissions.hasPermissions(this, perms)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, gs(R.string.app_need_permission), 0, perms);
        }
        return false;
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(CommonRequest.METHOD_UPLOAD_FILE)) {
            Upload upload = (Upload) entity;
            /*String avatarUrl = Config.getUrl() + "/" + upload.getData();
            L.GL.d("avatarUrl[%s]", avatarUrl);
            UserInfo userInfo = mMineFragment.getBinding().getUser();
            if (userInfo != null) {
                userInfo.setUserImagePathFull(avatarUrl);
            }*/
            mGeneralManager.getRequestManager()
                           .getUserRequest()
                           .updateInfo(null, null, null, upload.getData(), this)
                           .execute();
        } else if (method.equals(UserRequest.METHOD_UPDATE_INFO)) {
            ToastUtil.showToast(this,"更新用户信息成功");
            closeLoadingDialog();
        } else if (method.equals(CommonRequest.METHOD_CHECK_UPDATE)) {
            Version.Response res = (Version.Response) entity;
            Version version = res.getData();
            if (version != null && version.hasUpdate()) {
                XApplication.getInstance().setCheckUpdate(true);
                UpdateDialogFragment.createInstance(version)
                        .show(getSupportFragmentManager(), "update");
            }
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(CommonRequest.METHOD_UPLOAD_FILE)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        } else if (method.equals(UserRequest.METHOD_UPDATE_INFO)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPhotoUtil.onActivityResult(requestCode, resultCode, data);
    }
}
